import Vue from 'vue';
import App from './App';
import router from './router';
import iView from 'iview';
import 'iview/dist/styles/iview.css';
import axios from 'axios';

Vue.use(iView);
Vue.config.productionTip = false;

Vue.prototype.$axios = axios;

router.beforeEach((to, from, next) => {
  if (sessionStorage.token) { // 判断是否有token
    if (to.path === '/login') {
      next({ path: '/home' });
    } else {
      next();
    }
  } else {
    if (to.path !== '/login') {
      next('/login'); // 否则全部重定向到登录页
    } else {
      next();
    }
  }
});

axios.defaults.baseURL = process.env.API;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  iView.Spin.show({
    render: (h) => {
      return h('div', [
        h('Icon', {
          'class': 'demo-spin-icon-load',
          props: {
            type: 'load-c',
            size: 18,
          },
        }),
        h('div', 'Loading'),
      ]);
    },
  })
  config.url += '?token=' + sessionStorage.token;
  return config;
}, function (error) {
  // 对请求错误做些什么
  iView.Spin.hide()
  iView.Message.error('网络请求异常')
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  iView.Spin.hide()
  if (response.data.code === 200) {
    return response.data.data;
  } else {
    iView.Message.error(response.data.msg)
    return Promise.reject(response.data.msg);
  }
}, function (error) {
  // 对响应错误做点什么
  iView.Spin.hide()
  return Promise.reject(error);
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
});
